package com.yxp423.ssmempl.service.impl;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.yxp423.ssmempl.service.IQiniuService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-07-31 20:38
 * @Version: 1.0
 */
@Service
public class QiniuServiceImpl implements IQiniuService, InitializingBean {

	@Autowired
	private UploadManager uploadManager;

	@Autowired
	private Auth auth;


	@Autowired
	private BucketManager bucketManager;

	@Value("${qiniu.bucket}")
	private String bucket;

	StringMap putPolicy;


	@Override
	public Response uploadFile(File file) throws QiniuException {
		return null;
	}

	@Override
	public Response uploadFile(InputStream inputStream) throws QiniuException {

		Response response = uploadManager.put(inputStream, null, getUploadToken(), null, null);

		int retry = 0;

		while (response.needRetry() && retry < 3) {

			response = uploadManager.put(inputStream, null, getUploadToken(), null, null);

			retry++;

		}

		return response;
	}

	@Override
	public Response delete(String key) throws QiniuException {
		return null;
	}


	/**
	 * 生成上传凭证
	 *
	 * @return
	 */
	public String getUploadToken() {

		return this.auth.uploadToken(bucket, null, 3600, putPolicy);

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.putPolicy = new StringMap();
		putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
	}
}
